<?php
class Article{
	public $path='../blogdata/';		//blogdata目录与 类 目录相对位置
	private $err_goto;
	function __construct($page='index.php'){
		$this->err_goto=$page;
		date_default_timezone_set('PRC');
	}
//写博客
	function writeBlog($title,$content,$category_id,$uid){
		if(!(is_numeric($category_id)&&is_numeric($uid)))
			die('<script>alert("输入错误");location="'.$this->err_goto.'";</script>');
		$ctime=time();
		$tt=urlencode($title);
		$path=$this->path.$uid.'/'.date('Ymd',$ctime).'/'.$tt;
		$sql='insert into blog values(null,"'.$tt.'"';
		$sql.=',"'.$this->path.'"';		//文章内容,储存路径:$path
		$sql.=','.$category_id;		//		bicool/blogdata/1/2013512/article123455233123
		$sql.=',"checking"';
		$sql.=','.$uid;
		$sql.=','.$ctime;
		$sql.=','.$ctime;			//modify_time
		$sql.=',0,0,0,0)';
		$this->runMysql($sql);

		$this->makedir($path);
		file_put_contents($path,$content);	// 写入文章内容
		
	}
//添加评论
	function setComments($uid,$content,$aid,$tofloor=null){	//GET传输，输入错误时跳转的页面
		if((!is_numeric($aid)&&is_numeric($uid)))			//articl id不是数字的时候，结束程序，弹出错误
			die('<script>alert("输入错误");location="'.$this->err_goto.'";</script>');
		$time=time();
		$r=$this->runMysql('select user_id,create_time,title from blog where id='.$aid);
		$commentsPath=$this->path.$r[0]['user_id'].'/'.date('Ymd',$r[0]['create_time']).'/'.$r[0]['title'].'c'.'/'.$time;	//用户目录下/日期/comments/$time
		if($tofloor)									//设置楼层信息，没有指定回复楼层$tofloor，便执行楼层+1
			$floor=$tofloor;
		else{
			$f=$this->runMysql('select floor from comments where blog_id='.$aid.' order by floor desc limit 1');
			if($f[0]['floor'])
				$floor=$f[0]['floor']+1;
			else
				$floor=1;
		}
		$sql='insert into comments values(null,'.$uid.','.$aid.',"'.$commentsPath.'",'.$floor.','.$time.')';
		$this->runMysql($sql);
		$this->makedir($commentsPath);
		file_put_contents($commentsPath,$content);
		return true;
	}
//设置评分
	function setScore($score,$aid){	//score_count score_total
		$r=$this->runMysql('select score_total,score_count from blog where id='.$aid);
		$sc=$r[0]['score_count']+1;
		$st=$r[0]['score_total']+$score;
		$sql1='update blog set score_total='.$st;
		$this->runMysql($sql1);
		$sql2='update blog set score_count='.$sc;
		$this->runMysql($sql2);
	}


// 最新文章，$num 为显示数量
	function getLatest($num,$page=1,$flag='modify_time'){
		if(!(is_numeric($num)&&is_numeric($page)))					//articl id不是数字的时候，结束程序，弹出错误
			die('<script>alert("输入错误");location="'.$this->err_goto.'";</script>');
		
		$sql1='select id,title,category_id,user_id,create_time,modify_time,publish_time,click_count,score_total,score_count from blog where check_status="checked"';
		$sql1.='order by '.$flag.' desc limit '.(($page-1)*$num).','.$num;
		$r1=$this->runMysql($sql1);
		$artInfo=array();
		$count=count($r1);
		for($i=0;$i<$count;$i++){
			$artInfo[$i]['aid']=$r1[$i]['id'];		//作者
			$artInfo[$i]['title']=urldecode($r1[$i]['title']);
			$uid[$i]=$r1[$i]['user_id'];			//作者id
			$cat=$this->getCategory($r1[$i]['category_id']);	//runMysql('select type from category where id='.$r1[$i]['category_id']);
			$artInfo[$i]['category']=$cat;		//文章类型

			$artInfo[$i]['writer']=$this->getUsername($uid[$i]);
			if($r1[$i]['score_count'])
				$artInfo[$i]['score']=round($r1[$i]['score_total']/$r1[$i]['score_count'],1);	//评分
			else
				$artInfo[$i]['score']=0;

			$artInfo[$i]['create_time']=$r1[$i]['create_time'];		//创建时间
			$artInof[$i]['publish_time']=$r1[$i]['publish_time'];	//发表时间
			$artInfo[$i]['modify_time']=$r1[$i]['modify_time'];		//最后一次修改时间
			$artInfo[$i]['click_count']=$r1[$i]['click_count'];		//点击量

		}
		// $artInfo包含变量:aid,title,writer,score,category,create_time,publish_time,modify_time,click_count
		return $artInfo;
	}
//查询上一篇，下一篇文章id
	function getNearAid($aid){
		if(!(is_numeric($aid)))					//articl id不是数字的时候，结束程序，弹出错误
			die('<script>alert("输入错误");location="'.$this->err_goto.'";</script>');
		
		include 'connect.inc.php';
		$sql_current='select modify_time mt from blog where id='.$aid;
		$row=$mysqli->query($sql_current);
		$current=$row->fetch_assoc();
		$sql_later='select id,title from blog where check_status="checked" and modify_time>'.$current['mt'].' order by modify_time limit 1';
		$sql_former='select id,title from blog where check_status="checked" and modify_time<'.$current['mt'].' order by modify_time desc limit 1';
		$later=$mysqli->query($sql_later);
		$former=$mysqli->query($sql_former);
		
		$output['later']=$later->fetch_assoc();
		$output['former']=$former->fetch_assoc();
		$output['later']['title']=urldecode($output['later']['title']);
		$output['former']['title']=urldecode($output['former']['title']);
		$mysqli->close();
		return $output;
	}

//显示文章内容、评论等的详细情况,$detail为true时,显示内容
	function getBlogDetail($aid,$check_status='checked'){		//click_count	
		if(!is_numeric($aid))					//articl id不是数字的时候，结束程序，弹出错误
			die('<script>alert("输入错误");location="'.$this->err_goto.'";</script>');
		//设置点击量
		$r=$this->runMysql('select click_count cc from blog where id='.$aid);
		$click=$r[0]['cc']+1;
		$this->runMysql('update blog set click_count='.$click.' where id='.$aid);
/*		if($check_status=='all')
			$check='';
		else
			$check=' check_status="'.$check_status.'" and';
 */
		$sql1='select title,content,category_id,user_id,create_time,modify_time,publish_time,click_count,score_total,score_count';
		$sql1.=' from blog where id='.$aid;
		$r1=$this->runMysql($sql1);

		$artInfo=array();
		$artInfo['title']=urldecode($r1[0]['title']);
		$uid=$r1[0]['user_id'];			//作者id
		$cat=$this->runMysql('select type from category where id='.$r1[0]['category_id']);
		$artInfo['category']=$cat[0]['type'];		//文章类型
		$user=$this->runMysql('select user from user where id='.$uid);
		$artInfo['writer']=$user[0]['user'];		//作者
		if($r1[0]['score_count'])
			$artInfo['score']=round($r1[0]['score_total']/$r1[0]['score_count'],1);	//评分
		//json,js  eval取出php输出


		$path=$this->path.$uid.'/'.date('Ymd',$r1[0]['create_time']).'/'.$r1[0]['title'];
		$content=file_get_contents($path);
		$artInfo['content']=$content;
		$artInfo['create_time']=$r1[0]['create_time'];	//创建时间
		$artInfo['publish_time']=$r1[0]['publish_time'];	//发表时间
		$artInfo['modify_time']=$r1[0]['modify_time'];	//最后一次修改时间
		$artInfo['click_count']=$r1[0]['click_count'];	//点击量
// $artInfo包含变量:title,writer,score,category,content,create_time,publish_time,modify_time,click_count
		return $artInfo;
	}

//显示评论
	function getComments($aid,$order=null){
		if(!is_numeric($aid))					//articl id不是数字的时候，结束程序，弹出错误
			die('<script>alert("输入错误");location="'.$this->err_goto.'";</script>');
		$sql='select id,content,time,floor,user_id from comments where blog_id='.$aid.' order by floor,time '.$order;
		$row=$this->runMysql($sql);
		$awid=$this->runMysql('select user_id,create_time,title from blog where id='.$aid);	//article writer id
		$count=count($row);
		for($i=0;$i<$count;$i++){
			$path=$this->path.$awid[0]['user_id'].'/'.date('Ymd',$awid[0]['create_time']).'/'.$awid[0]['title'].'c/'.$row[$i]['time'];
			$comments[$i]['content']=file_get_contents($path);
			$comments[$i]['replier']=$this->getUsername($row[$i]['user_id']);
			$comments[$i]['repl_id']=$row[$i]['user_id'];
			$comments[$i]['time']=$row[$i]['time'];
			$comments[$i]['floor']=$row[$i]['floor'];
			$comments[$i]['cid']=$row[$i]['id'];
		}
		//对floor排序，floor相同的，以time顺序排列

		return $comments;
	}
//显示最近浏览跟新回复
	function getLatestComments($num=10){
		$sql='select user_id,blog_id,content from comments where blog_id in (select id from blog where check_status="checked") order by time desc limit '.$num;
		$re=$this->runMysql($sql);
		$count=count($re);
		for($i=0;$i<$count;$i++){
			$re[$i]['content']=file_get_contents($re[$i]['content']);
			$re[$i]['replier']=$this->getUsername($re[$i]['user_id']);
		}
		return $re;
	}
//点击量最高
	function getHighestClick($num=10){
		$sql='select id,title,category_id,click_count from blog where check_status="checked"';
		$sql.='order by click_count desc limit '.$num;
		$hc=$this->runMysql($sql);
		$count=count($hc);
		for($i=0;$i<$count;$i++){
			$hc[$i]['title']=urldecode($hc[$i]['title']);
			$hc[$i]['category']=$this->getCategory($hc[$i]['category_id']);
		}
		return $hc;
	}
//求数据库的文章数目，用于分页
	function blog_count($check_status='all'){
		if($check_status=='all')
			$sql='select id from blog where check_status="checked"';
		else
			$sql='select id from blog where check_status="'.$check_status.'"';
		$r=$this->runMysql($sql);
		return count($r);
	}
//删除文章、评论
	function deleteBlog($aid){
		$del=$this->runMysql('select user_id,create_time,title from blog where id='.$aid);
		$blog=$this->path.$del[0]['user_id'].'/'.date('Ymd',$del[0]['create_time']).'/'.$del[0]['title'];
		$comments=$this->path.$del[0]['user_id'].'/'.date('Ymd',$del[0]['create_time']).'/'.$del[0]['title'].'c';
		$this->deleteFile($blog);
		$this->deleteFile($comments);
		$this->runMysql('delete from comments where blog_id='.$aid);
		$this->runMysql('delete from blog where id='.$aid);
		$file_b=file_exists($blog);
		$file_c=file_exists($comments);
		$dele_b=$this->runMysql('select * from blog where id='.$aid);
		$dele_c=$this->runMysql('select * from comments where blog_id='.$aid);

		if($file_b||$file_c||$dele_b||$dele_c)
			return false;
		else 
			return true;

	}
//获取分类、或者以category id求出分类名
	function getCategory($catId='all'){
		$sql='';
		if(is_numeric($catId))
			$sql='select type from category where id='.$catId;
		elseif($catId=='all')
			$sql='select id,type from category';
		if(!$sql)
			return false;
		$result=$this->runMysql($sql);
		$count=count($result);
		if($count==1){
			$cat=$result[0]['type'];
		}else{
			for($i=0;$i<$count;$i++)
				$cat[$i]=urldecode($result[$i]['type']);
		}
		return $cat;
	}
//数据库查询函数，参数：数据库名称，查询内容，查询条件
	private function runMysql($sql){
		include 'connect.inc.php';
		$result=$mysqli->query($sql);
		if($mysqli->error)
			echo $mysqli->error;
		if(is_object($result)){			//插入或者是错误时，返回bool值
			$output=array();			//插入时，不赋值给变量
			for($i=0;$row=$result->fetch_assoc();$i++){
				$output[$i]=$row;
			}
			return $output;				//返回一个二维数组
		}
		$mysqli->close();
	}
//根据用户id获取用户名username
	private function getUsername($uid){	
		$user=$this->runMysql('select user from user where id='.$uid);
		$username=$user[0]['user'];		//作者
		return $username;
	}

//路径创建函数
	private function makedir($path){
		$arr=explode('/',$path);
		$num=count($arr);
		$p='';
		for($i=0;$arr[$i+1];$i++){
			$p.=$arr[$i].'/';
			if(!file_exists($p))
				mkdir($p);
		}
	}
//文件删除函数
	private function deleteFile($fileName){
		if(file_exists($fileName)){
			if(is_file($fileName))
				unlink($fileName);
			else{
				$dirHandle=opendir($fileName);
				while($dir=readdir($dirHandle)){
					if($dir!='.'&&$dir!='..'){
						$dir=$fileName.'/'.$dir;
						$this->deleteFile($dir);
					}
				}
				rmdir($fileName);
			}	
		}
	}
}
